package com.arceus.leetcode;

import java.util.*;

/**
 * @author : iron
 * @version : 1.0.0
 * @date : 3:17 PM 2019/3/4
 */

public class T841 {

    public static boolean canVisitAllRooms(List<List<Integer>> rooms) {
        Set<Integer> r = new HashSet<>();
        Set<Integer> k = new HashSet<>();

        if (rooms.size() == 1) {
            return true;
        }
        List<Integer> room1 = rooms.get(0);
        for (Integer keys : room1) {
            r.add(0);
            k.add(keys);
        }
        return keys(r, k, rooms);

    }

    public static boolean keys(Set<Integer> r, Set<Integer> k, List<List<Integer>> rooms) {
        Set<Integer> tmp = new HashSet<>();
        Iterator<Integer> it = k.iterator();
        while (it.hasNext()) {
            Integer key = it.next();
            if (!r.contains(key)) {
                r.add(key);
                List<Integer> room = rooms.get(key);
                for (Integer keys : room) {
                    tmp.add(keys);
                }
            }
            it.remove();
        }
        k.addAll(tmp);

        if (k.size() != 0) {
            keys(r, k, rooms);
        }
        if (r.size() == rooms.size()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> rooms = new ArrayList<>();
        List<Integer> room = new ArrayList<>();
        room.add(1);
        rooms.add(room);
        List<Integer> room1 = new ArrayList<>();
        room1.add(2);
        rooms.add(room1);
        List<Integer> room2 = new ArrayList<>();
        rooms.add(room2);
        canVisitAllRooms(rooms);
    }

}
